/*
 * $Id: Function.java,v 1.7 2003/06/29 10:52:30 znamenacek Exp $
 *
 * Copyright (c) Tomas Znamenacek
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package net.sf.vofce.guts;

import java.util.Stack;

/**
 * A function.
 *
 * @author Tomas Znamenacek
 */
public class Function {

	/**
	 * The body of this function in an evaluation-friendly format.
	 * Actually this is the root node of the expression tree.
	 */
	protected Operator rootNode;

	/**
	 * The function as entered by user.
	 * This is for user's convenience&mdash;we do many changes in the
	 * string the user enters (remove syntax sugar, for example) so we
	 * keep the string entered by user.
	 */
	protected String userView = null;

	/**
	 * Create a new function from its string representation.
	 */
	public Function(String body) throws Exception {

		Parser parser = new Parser();
		rootNode = parser.buildTree(body);
		userView = body;
	}

	/**
	 * Evaluate the function value in a given point.
	 * Returns <code>Double.NaN</code> if things go funky.
	 */
	public double evaluate(double point) {

		Variable.setValue(point);
		return rootNode.evaluateSubTree();
	}

	/**
	 * Returns function representation in simple human notation.
	 */
	public String toString() {

		return rootNode.toString(Integer.MIN_VALUE);
	}
	
	/**
	 * Returns function representation in TeX notation.
	 */
	public String toTeX() {

		return rootNode.toTeX(Integer.MIN_VALUE);
	}
	
	/**
	 * Returns function representation in MathML notation.
	 */
	public String toXML() {

		return rootNode.toXML(Integer.MIN_VALUE);
	}

	/** Returns the user string representing this function. */
	public String getUserView() {

		return (userView == null) ? toString() : userView;
	}
}
